#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include "ThreadPool.hpp"
#include "InetAddr.hpp"
#include "LockGuard.hpp"

using namespace std;
using task_t = function<void()>;

class MessageRoute
{
private:
    bool IsExist(const InetAddr &addr)
    {
        for (auto &a : _online_users)
        {
            if (a == addr)
            {
                return true;
            }
        }
        return false;
    }

public:
    MessageRoute()
    {
        pthread_mutex_lock(&_mutex);
    }

    void AddUser(const InetAddr &addr)
    {
        LockGuard l(&_mutex);
        if (IsExist(addr))
        {
            return;
        }
        _online_users.push_back(addr);
    }

    void DelUser(const InetAddr &addr)
    {
        LockGuard l(&_mutex);
        for (auto iter = _online_users.begin(); iter < _online_users.end(); iter++)
        {
            if (*iter == addr)
            {
                _online_users.erase(iter);
                break;
            }
        }
    }

    void RouteHelper(int sockfd, string message, InetAddr addr)
    {
        LockGuard l(&_mutex);
        for (auto u : _online_users)
        {
            string send_message = "[" + addr.Ip() + ":" + to_string(addr.Port()) + "]# " + message + "\n";
            struct sockaddr_in clientaddr = u.getAddr();
            sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr*)&clientaddr, sizeof(clientaddr));
        }
    }

    void Route(int sockfd, string message, InetAddr addr)
    {
        AddUser(addr);
        if(message == "q" || message == "quit")
        {
            DelUser(addr);
        }

        task_t t = bind(&MessageRoute::RouteHelper, this, sockfd, message, addr);
        ThreadPool<task_t> *tp = new ThreadPool<task_t>();
        tp->InitThreadPool();
        tp->Start();
        tp->Enqueue(t);
    }

    ~MessageRoute()
    {
        pthread_mutex_unlock(&_mutex);
    }

private:
    vector<InetAddr> _online_users;
    pthread_mutex_t _mutex;
};
